/* 
 * 1169774483@qq.com
 * 声明一个Util 对象
 * 封装app调用公用方法
 */
var Util = new Object;
// app接口地址域名
Util.HTTP = 'http://192.168.0.16:1505/';  //'http://192.168.0.16:1505/'  'http://www.tech-zone.cn:1505/';

// 获取日期
Util.getNowDate = function () {
	var date = new Date();
	var sign1 = "-";
	var sign2 = ":";
	var year = date.getFullYear() // 年
	var month = date.getMonth() + 1; // 月
	var day = date.getDate(); // 日
	var hour = date.getHours(); // 时
	var minutes = date.getMinutes(); // 分
	var seconds = date.getSeconds() //秒
	var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
	var week = weekArr[date.getDay()];
	// 给一位数数据前面加 “0”
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (day >= 0 && day <= 9) {
		day = "0" + day;
	}
	if (hour >= 0 && hour <= 9) {
		hour = "0" + hour;
	}
	if (minutes >= 0 && minutes <= 9) {
		minutes = "0" + minutes;
	}
	if (seconds >= 0 && seconds <= 9) {
		seconds = "0" + seconds;
	}
	var currentdate = {
		year: year,
		month: month,
		day: day,
		week: week,
		time: year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds
	}
	return currentdate;
}



Util.timeago = function (dateTimeStamp) { //dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
	if (!dateTimeStamp) return
	var reg = /(\d{4})\-(\d{2})\-(\d{2})/;
	var Newdate = dateTimeStamp.replace(reg, "$1/$2/$3");
	var dateTime = new Date(Newdate).getTime()
	var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
	var hour = minute * 60;
	var day = hour * 24;
	var week = day * 7;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime(); //获取当前时间毫秒
	var diffValue = now - dateTime; //时间差

	if (diffValue < 0) {
		return;
	}
	var minC = diffValue / minute; //计算时间差的分，时，天，周，月
	var hourC = diffValue / hour;
	var dayC = diffValue / day;
	var weekC = diffValue / week;
	var monthC = diffValue / month;
	if (monthC >= 1 && monthC <= 3) {
		result = " " + parseInt(monthC) + "月前"
	} else if (weekC >= 1 && weekC <= 3) {
		result = " " + parseInt(weekC) + "周前"
	} else if (dayC >= 1 && dayC <= 6) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		var datetime = new Date();
		datetime.setTime(dateTime);
		var Nyear = datetime.getFullYear();
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate
	}
	return result;
}




// 设置缓存
Util.setState = function (name, data) {
	if (typeof name == "string") {
		plus.storage.setItem(name, JSON.stringify(data))
	} else {
		console.log('传入的' + name + '：不是一个字符串')
	}

}

// 获取缓存
Util.getState = function (name) {
	if (typeof name == "string") {
		var data = plus.storage.getItem(name) || {}
		if (typeof data == 'object'){
			data = JSON.stringify(data); 
		}
		return JSON.parse(data);
	} else {
		console.log('传入的' + name + '：不是一个字符串')
	}
}

// 清楚指定的缓存
Util.removeItem = function (name) {
	if (typeof name == "string") {
		plus.storage.removeItem(name);
	} else {
		console.log('传入的' + name + '：不是一个字符串')
	}
}

// 获取系统电量栏高度
Util.StatusbarHeight = function (id) {
	var App = document.getElementById(id)
	App.style.paddingTop = plus.navigator.getStatusbarHeight() + 'px'
}

// 获取小区列表
Util.GetNeighborhoodsType = function (back) {
	mui.post(Util.HTTP + 'api/Building/GetNeighborhoods', {}, function (res) {
		console.log(res.code)
		if (res.code == 1001) {
			var list = []
			res.data.forEach(function (item, index) {
				var value = item.neiID
				var text = item.neiName
				list.push({
					value: value,
					text:text
				})
			})
			back(list)
		} else {
			mui.toast(res.code + '：请求错误')
		}
	})
}

// 获取楼宇
Util.GetBuilding = function (ID, back) {
	mui.post(Util.HTTP + 'api/Building/GetBuilding', {
		neiID: ID
	}, function (res) {
		if (res.code == 1001) {
			var list = []
			res.data.forEach(function (item, index) {
				var value = item.buiID
				var text = item.buiName
				list.push({
					value: value,
					text:text
				})
			})
			back(list)
		} else {
			mui.toast(res.code + '：请求错误')
		}
	})
}

// 获取单元
Util.GetElement = function (ID, back) {
	mui.post(Util.HTTP + 'api/Building/GetElement', {
		buiID: ID
	}, function (res) {
		if (res.code == 1001) {
			var list = []
			res.data.forEach(function (item, index) {
				var value = item.eleID
				var text = item.eleName
				list.push({
					value: value,
					text: text
				})
			})
			back(list)
		} else {
			mui.toast(res.code + '：请求错误')
		}
	})
}


// 获取房间
Util.GetRoom = function (ID, back) {
	mui.post(Util.HTTP + 'api/Building/GetRoom', {
		eleID: ID
	}, function (res) {
		console.log(res.code)
		if (res.code == 1001) {
			var list = []
			res.data.forEach(function (item, index) {
				var value = item.roomID
				var text = item.roomEncode
				list.push({
					value: value,
					text: text
				})
			})
			back(list)
		} else {
			mui.toast(res.code + '：请求错误')
		}
	})
}

// 拍照
Util.Photograph = function (black) {
	var c = plus.camera.getCamera();
	c.captureImage(function (e) {
		//存储到本地 
		plus.io.resolveLocalFileSystemURL(e, function (entry) {
			black(entry.toLocalURL())
		}, function (e) {
			console.log("读取拍照文件错误：" + e.message);
		});
	}, function (s) {
		console.log("error" + s);
	}, {
		filename: "_doc/head.jpg"
	})
}



// 打开手机相册选择图片
Util.OpenPhoto = function (black) {
	plus.gallery.pick(function (a) {
		plus.io.resolveLocalFileSystemURL(a, function (entry) {　　　
			black(entry.toLocalURL());
		}, function (e) {
			console.log("读取图片错误：" + e.message);
		});
	}, function (a) {}, {
		filter: "image"
	})
}


//上传用户头像

Util.IconUploadProprietor = function (data, callback) {
	mui.post(Util.HTTP + 'api/Files/IconUpload', {
		periID: data.periID,
		IconStr: data.imgSrc,
	}, function (res) {
		if (res.code == 1001) {
			callback()
		} else {
			mui.toast('头像上传失败,请重试')
		}
	})
}

// 默认打开键盘事件

Util.openSoftKeyboard = function () {
	if (mui.os.ios) {
		var webView = plus.webview.currentWebview().nativeInstanceObject();
		webView.plusCallMethod({
			"setKeyboardDisplayRequiresUserAction": false
		});
	} else {
		var webview = plus.android.currentWebview();
		plus.android.importClass(webview);
		webview.requestFocus();
		var Context = plus.android.importClass("android.content.Context");
		var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
		var main = plus.android.runtimeMainActivity();
		var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
	}
}

// 判断手机号
Util.phone = function (phone) {
	var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
	if (phone.length < 11) {
		mui.toast('手机号码最短需要 11 个位')
		return false
	} else {
		if (!myreg.test(phone)) {
			mui.toast('手机号格式有误！')
			return false
		}
	}
	return true
}

// 判断密码正则
Util.checkPassword = function (str) {
	var reg1 = /[!@#$%^&*()_?<>{}]{1}/;
	var reg2 = /([a-zA-Z0-9!@#$%^&*()_?<>{}]){6,16}/;
	var reg3 = /[a-zA-Z]+/;
	var reg4 = /[0-9]+/;
	if (reg2.test(str) && reg3.test(str) && reg4.test(str)) {
		return true;
	} else if (!reg2.test(str)) {
		mui.toast("长度在6-16位");
		return false;
	} else if (!reg3.test(str)) {
		mui.toast("需含有字母");
		return false;
	} else if (!reg4.test(str)) {
		mui.toast("需含有数字");
		return false;
	}
}

// 请求短信接口
Util.SendSMSVerify = function (phone) {
	mui.post(Util.HTTP + 'api/Users/SendSMSVerify', {
		phone: phone
	}, function (res) {
		mui.toast(res.message)
	})
}


// 获取验证码的方法
Util.getCode = function (phone, callback) {
	if (!Util.phone(phone)) {
		return
	}
	var time = 60;
	var codetxt, codeBtn
	console.log('请求短信接口') 
	Util.SendSMSVerify(phone) // 调用请求短信接口
	var countdown = setInterval(function () {
		if (time <= 1) {
			clearInterval(countdown)
			codetxt = '重新获取';
			codeBtn = false;
		} else {
			time--
			codetxt = time + 's后获取';
			codeBtn = true
		}
		return callback(codetxt, codeBtn)
	}, 1000)
}


//收藏
Util.AddCollecting = function (id, type) {
	mui.post(Util.HTTP + 'api/Collecting/AddCollecting', {
		userID: Util.getState('$state').userID,
		collectingBizID: id,
		collectingBizType: type
	}, function (res) {
		if (res.code == 1001) {
			mui.toast('收藏成功')
		} else {
			mui.toast(res.message)
		}

	})
}

// 取消收藏
Util.CancelCollecting = function (id, type) {
	mui.post(Util.HTTP + 'api/Collecting/CancelCollecting', {
		userID: Util.getState('$state').userID,
		collectingBizID: id,
		collectingBizType: type
	}, function (res) {
		if (res.code == 1001) {
			mui.toast('取消成功')
		} else {
			mui.toast(res.message)
		}
	})
}


// 点赞 
Util.AddLikes = function (dynID) {
	mui.post(Util.HTTP + 'api/Likes/AddLikes', {
		dynID: dynID, //动态ID
		userID: Util.getState('$state').userID //账号ID
	}, function (res) {
		if(res.code!= 1001){
			mui.toast(res.message)
		}
	})
}

// 取消点赞 
Util.DeleteLikes = function (dynID) {
	mui.post(Util.HTTP + 'api/Likes/DeleteLikes', {
		dynID: dynID, //动态ID
		userID: Util.getState('$state').userID //账号ID
	}, function (res) {
		if(res.code!= 1001){
			mui.toast(res.message)
		}
	})
}
